<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/7/22  8:59
// +----------------------------------------------------------------------
namespace  Service;
require_once COMMON_PATH . 'WxpayAPI/example/WxPay.JsApiPay.php';
require_once COMMON_PATH . "WxpayAPI/lib/WxPay.Api.php";
class WechatService {
    const appid = 'wxc381b6c916cd12e0';
    const sercret = 'c47b5734214deb6d3d844a83a18cab00';
    const mchid = '1243290602';
    const key = '847804a5d92917236f83cb69d5d4d873';
    function __construct($container) {
        $this->di=$container;
    }
    //获取AccessToken
    public function  getToken(){
        $access_token = S('access_token');
        if (empty($access_token)) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . self::appid . '&secret=' . self::sercret;
            $str = file_get_contents($url);
            $str = json_decode($str, true);
            $access_token = $str['access_token'];
            S('access_token', $access_token, $str['expires_in']);
        }
        return $access_token;
    }
    //获取素材
    public function getMaterial($type='news',$offset=0,$count=3){

        $access_token=self::getToken();
        $wechat_material=S('wechat_material');
        if(empty($wechat_material)){
            $url='https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token='.$access_token;
            $postdata=[
                'type'=>$type,  //  图片（image）、视频（video）、语音 （voice）、图文（news）
                'offset'=>$offset,
                'count'=>$count
            ];
            $wechat_material=postSend($url,json_encode($postdata));
            //缓存10分钟
            S('wechat_material',$wechat_material,600);
        }
        $wechat_material=json_decode($wechat_material,true);
        return $wechat_material;
    }
    //获取微信打开的URL,用于获取code获取用户数据等的URL
    public function getWxUrl($url,$state='123'){
        $url=urlencode($url);
        $wxurl='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.self::appid.'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect';
        return $wxurl;
    }
    //清理缓存数据
    public function clear(){
        S('access_token', null);
        S('wechat_material', null);
    }

    //微信通知
    public static function  weixin_notice($user,$content){
        $access_token = WechatService::getToken();

        $url='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='. $access_token;
        $data='{
        "touser":"'.$user['openid'].'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';
        $result=postSend($url,$data);
        PublicService::log('通知',$result.$content);
        $result=json_decode($result);

        if($result->errcode==0){
            return true;
        }else{
            return $result->errcode;
        }
    }

    public function wx_refund($refund_money,$pay_id){

        //微信退款
        $input = new \WxPayRefund();
        $input->SetOut_trade_no(\WxPayConfig::MCHID  . $pay_id);

        $input->SetTotal_fee($refund_money*100);
        $input->SetRefund_fee($refund_money*100);
        $input->SetOut_refund_no(\WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOp_user_id(\WxPayConfig::MCHID);

        $wxr=\WxPayApi::refund($input);
        if($wxr['result_code']=='SUCCESS'){
            $r=[
                'status'=>'success',
                'data'=>'退款成功'
            ] ;
        }else{
            $r=[
                'status'=>'error',
                'data'=>$wxr
            ] ;
        }
        return $r;

    }
}